import React, { memo } from "react";
import { FlatList, Text, TouchableOpacity, View } from "react-native";
import { Sentence, Transcription } from "../constants/types";

const SentenceCard = memo(function SentenceCard({
  sentence,
  currentTime,
  onPress,
  onActive,
}: {
  sentence: Sentence;
  currentTime: number;
  onPress: (time: number) => void;
  onActive: (sentence: Sentence) => void;
}) {
  const isActive = currentTime >= sentence.start && currentTime <= sentence.end;
  if (isActive) {
    onActive(sentence);
  }
  return (
    <TouchableOpacity
      onPress={() => onPress(sentence.start)}
      style={{
        backgroundColor: isActive ? "#e0e0e0" : "transparent",
        paddingVertical: 16,
        paddingHorizontal: 8,
        margin: 8,
        borderRadius: 12,
      }}
    >
      <View style={{ flexWrap: "wrap", flexDirection: "row" }}>
        {sentence.words.map((word, idx) => {
          const isWordActive =
            currentTime >= word.start && currentTime <= word.end;
          return (
            <View
              key={`word-${idx}`}
              style={{
                paddingHorizontal: 6,
                paddingVertical: 4,
                minHeight: 28,
                borderWidth: 2,
                borderColor: isWordActive ? "#4CAF50" : "transparent",
                borderRadius: 8,
                marginVertical: 6,
                justifyContent: "center",
              }}
            >
              <Text style={{ fontSize: 16, fontWeight: "bold" }}>
                {word.word.trim()}
              </Text>
            </View>
          );
        })}
      </View>

      <Text
        style={{
          fontSize: 16,
          paddingHorizontal: 8,
          color: "#666",
          lineHeight: 30,
        }}
      >
        {sentence.translation}
      </Text>
    </TouchableOpacity>
  );
});

export default function TranscriptList({
  data,
  currentTime,
  onPress,
  onActive,
}: {
  data: Transcription;
  currentTime: number;
  onPress: (time: number) => void;
  onActive: (sentence: Sentence) => void;
}) {
  return (
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <SentenceCard
          onActive={onActive}
          sentence={item}
          currentTime={currentTime}
          onPress={onPress}
        />
      )}
      contentContainerStyle={{
        paddingBottom: 800,
      }}
      keyExtractor={(item) => item.id.toString()}
    />
  );
}
